<template>
  <el-drawer
    v-model="visible"
    title="关联门禁设备"
    size="500px"
    :destroy-on-close="true"
    @closed="onDrawerClosed"
  >
    <div v-loading="loading">
      <template v-if="faceLockList.length > 0">
        <div class="primary-section pv-12 ph-16 mb-10" v-for="item in faceLockList" :key="item.id">
          <el-row align="middle">
            <el-col :span="16">
              <span class="font-w">{{ item.faceLockName }}</span>
            </el-col>
            <el-col :span="8" align="right">
              <el-button type="primary" size="small" @click="() => bindFaceLock(item)">绑定</el-button>
            </el-col>
          </el-row>
        </div>
      </template>
      <el-empty v-else description="暂无可关联门禁设备" />
    </div>
  </el-drawer>
</template>

<script setup name="AssociateFaceLockDrawer">
import { ref, defineProps, defineEmits, getCurrentInstance } from 'vue'
import { getUnbindList, bindRoom } from '@/api/device/faceLock.js'

const { proxy } = getCurrentInstance()
const props = defineProps({
  roomId: {
    type: [Number, String],
    default: ''
  },
  modelValue: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'success', 'closed'])

const faceLockList = ref([])
const loading = ref(false)
const hasChanges = ref(false)

const visible = computed({
  get: () => props.modelValue,
  set: (val) => {
    emit('update:modelValue', val)
  }
})

watch(() => props.modelValue, (val) => {
  if (val && props.roomId) {
    getFaceLockList()
  }
})

// 获取可绑定门禁列表
function getFaceLockList() {
  loading.value = true
  faceLockList.value = []
  getUnbindList(props.roomId).then(res => {
    faceLockList.value = res.data || []
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

// 绑定门禁设备
function bindFaceLock(item) {
  // 将当前房间ID作为逗号分隔的字符串传递
  bindRoom(item.faceLockId, props.roomId).then(res => {
    proxy.$modal.msgSuccess('绑定成功')
    hasChanges.value = true
    getFaceLockList()
    emit('success')
  })
}

// 抽屉关闭时触发事件
function onDrawerClosed() {
  if (hasChanges.value) {
    emit('closed', true) // 传递一个参数表示有更改
  } else {
    emit('closed', false)
  }
  hasChanges.value = false
}
</script> 